<?php

namespace App\Http\Middleware;

use Tymon\JWTAuth\Facades\JWTAuth;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class JwtMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        try {
            // 尝试从 Token 中获取用户信息
            $user = JWTAuth::parseToken()->authenticate();

            // 将解析出的用户信息放入请求中，方便后续使用
            $request->merge(['user' => $user]);
            return $next($request);
        } catch (\Exception $e) {
            // Token 解析失败，处理异常
            return response()->json(['error' => 'Unauthorized'], 401);
        }
    }
}
